//
//  PreferenceController.m
//  QuickPost
//
//  Created by Chen Xianan on 2/3/09.
//  Copyright 2009 sk. All rights reserved.
//

#import "PreferenceController.h"
#import "AppController.h"

@implementation PreferenceController

+ (void)initialize
{
	NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];
	[defaultValues setObject:[NSArray array] forKey:QP_ACCOUNTS_KEY];
	[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
}

- (id)init
{	
	if ([super initWithWindowNibName:@"Preference"])
		return self;
	
	return nil;
}

- (void)dealloc
{
	[services release];
	[_source release];
	[super dealloc];
}

- (void)awakeFromNib
{
	NSString *path = [[NSBundle mainBundle] pathForResource:@"services" ofType:@"plist"];
	services = [[NSDictionary dictionaryWithContentsOfFile:path] retain];
	[combo addItemsWithObjectValues:[services allKeys]];
	[combo selectItemAtIndex:1];
	[edit setEnabled:NO];
	[delete setEnabled:NO];
	[table setDataSource:self];
	[table setDelegate:self];
	_source = [[NSMutableArray arrayWithArray:[self tableSource]] retain];
}

- (void)addAccount:(id)sender
{
	NSString *key = [combo stringValue];
	NSArray *serv = [services valueForKey:key];
	if (!serv) return;
	NSString *acc = [account stringValue];
	if (![acc length]){
		[[account window] makeFirstResponder:account];
		return;
	}
	NSString *pass = [password stringValue];
	if (![pass length]){
		[[password window] makeFirstResponder:password];
		return;
	}
	NSArray *item = [[NSArray alloc] initWithObjects:key, [serv objectAtIndex:0], [serv objectAtIndex:1], acc, pass, nil];
	[_source addObject:item];
	[self setUserDefaults];
	[table reloadData];
	[account setStringValue:@""];
	[password setStringValue:@""];
}

- (void)deleteAccount:(id)sender
{
	NSInteger row = [table selectedRow];
	if (row == -1) return;
	[_source removeObjectAtIndex:row];
	[self setUserDefaults];
	[table reloadData];
}

- (void)setUserDefaults
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:_source forKey:QP_ACCOUNTS_KEY];
}

- (NSArray *)tableSource
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	return [defaults arrayForKey:QP_ACCOUNTS_KEY];
}

#pragma mark NSTableView Source
- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
	return [[self tableSource] count];
}

- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
			row:(NSInteger)rowIndex
{
	NSString *id = [aTableColumn identifier];
	NSArray *item = [[self tableSource] objectAtIndex:rowIndex];
	if ([id isEqualToString:@"service"]){
		return [item objectAtIndex:0];
	}
	return [item objectAtIndex:3];
}

#pragma mark NSTableView Delegate
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
	if ([table selectedRow] == -1){
		[edit setEnabled:NO];
		[delete setEnabled:NO];
	} else {
		[edit setEnabled:YES];
		[delete setEnabled:YES];
	}
}

@end
